﻿namespace Chunker.Inpe.Data {
    using System.Linq;
    using System.Data;
    using Chunker.Inpe.Data.SqlServer;

    public class ImageChunkController {
        public static int SaveChunk(IChunk chunk, int imageId) {
            using (var entities = new InpeEntitiesSqlServer()) {

                ImageChunk imageChunk = entities
                                            .ImageChunk
                                            .FirstOrDefault(x => x.ContentHash == chunk.Hash &&
                                                                 x.Start == chunk.Start &&
                                                                 x.End == chunk.End &&
                                                                 x.Image.ImageId == imageId);
                if (imageChunk != null) {
                    return imageChunk.ImageChunkId;
                }

                imageChunk = new ImageChunk();
                imageChunk.ImageReference.EntityKey = new EntityKey("InpeEntitiesSqlServer.Image", "ImageId", imageId);
                imageChunk.ContentHash = chunk.Hash;
                imageChunk.Start = chunk.Start;
                imageChunk.End = chunk.End;

                entities.AddToImageChunk(imageChunk);
                entities.SaveChanges();

                return imageChunk.ImageChunkId;
            }
        }
    }
}
